# 设置错误时停止执行
$ErrorActionPreference = "Stop"

# 配置
$frameworkPath = "framework"
$modulesPath = "modules"
$commonPropsPath = "common.props"

# 获取 common.props 中的版本信息
function Get-CommonPropsVersions {
    $commonProps = Get-Content $commonPropsPath -Raw
    
    # 获取 ABP 版本
    if ($commonProps -match '<AbpVersion>([\d\.]+)</AbpVersion>') {
        $abpVersion = $matches[1]
    } else {
        throw "无法从 common.props 中获取 ABP 版本"
    }
    
    # 获取 .NET 版本
    if ($commonProps -match '<DotNetVersion>([\d\.]+)</DotNetVersion>') {
        $dotNetVersion = $matches[1]
    } else {
        throw "无法从 common.props 中获取 .NET 版本"
    }
    
    return @{
        AbpVersion = $abpVersion
        DotNetVersion = $dotNetVersion
    }
}

# 更新项目文件
function Update-ProjectFile {
    param (
        [string]$projectPath
    )
    Write-Host "正在规范项目: $projectPath"
    $content = Get-Content $projectPath -Raw

    # 1. 统一 TargetFrameworks
    $content = $content -replace '<TargetFrameworks>.*?</TargetFrameworks>', '<TargetFrameworks>net$(DotNetVersion)</TargetFrameworks>'

    # 2. 统一 ABP 包引用（如 Volo.Abp.XXX、Volo.Abp.*）
    $content = $content -replace '(<PackageReference Include="Volo\.Abp\.[^"]+" )Version="[^"]+"', '$1Version="$(AbpVersion)"'

    # 3. 其它可选：如果有其它自定义包也想统一，可仿照上面加规则

    Set-Content -Path $projectPath -Value $content
}

# 获取所有项目文件
function Get-ProjectFiles {
    param (
        [string]$rootPath
    )
    return Get-ChildItem -Path $rootPath -Recurse -Filter "*.csproj"
}

# 主逻辑
try {
    # 获取版本信息
    $versions = Get-CommonPropsVersions
    Write-Host "ABP 版本: $($versions.AbpVersion)"
    Write-Host ".NET 版本: $($versions.DotNetVersion)"
    
    # 更新 framework 项目
    Write-Host "`n正在规范 framework 项目..."
    $frameworkProjects = Get-ProjectFiles -rootPath $frameworkPath
    foreach ($project in $frameworkProjects) {
        Update-ProjectFile -projectPath $project.FullName
    }
    
    # 更新 modules 项目
    Write-Host "`n正在规范 modules 项目..."
    $moduleProjects = Get-ProjectFiles -rootPath $modulesPath
    foreach ($project in $moduleProjects) {
        Update-ProjectFile -projectPath $project.FullName
    }
    
    Write-Host "`n所有项目已规范为引用 common.props 变量！"
} catch {
    Write-Error "发生错误: $_"
    exit 1
} 